<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      <el-breadcrumb-item>待销售单列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getOrdersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getOrdersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加订单</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格数据 -->
      <el-table
        :data="
          orderList.slice(
            (queryInfo.pageNum - 1) * queryInfo.pageSize,
            queryInfo.pageNum * queryInfo.pageSize
          )
        "
        border
        stripe
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="订单编号"
          prop="order_id"
          width="160px"
        ></el-table-column>
        <el-table-column
          label="下单客户"
          prop="order_customer"
          width="90px"
        ></el-table-column>
        <el-table-column label="订单操作" prop="order_is_pay" width="200px">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.order_is_pay == true"
              >已付款</el-tag
            >
            <el-tag type="danger" v-else>未付款</el-tag>
            <el-button
              v-if="scope.row.order_is_pay == false"
              size="small"
              type="success"
              round
              plain
              @click="confirmPay(scope.row.order_id)"
              >确认收款</el-button
            >
            <el-button
              v-else
              size="small"
              type="danger"
              round
              plain
              @click="finishOrder(scope.row)"
              >完成订单</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          label="产品"
          prop="order_product"
          width="100px"
        ></el-table-column>
        <el-table-column
          label="数量"
          prop="order_number"
          width="70px"
        ></el-table-column>
        <el-table-column
          label="订单价格"
          prop="order_price"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="下单管理员"
          prop="order_admin1"
          width="100px"
        ></el-table-column>
        <el-table-column label="下单时间" prop="order_time1" width="180px">
          <template slot-scope="scope">{{
            scope.row.order_time1 | dataFormat
          }}</template>
        </el-table-column>
        <el-table-column label="订单备注" prop="order_remark"></el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.order_id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.order_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>
    <!-- 添加订单的对话框 -->
    <el-dialog
      title="创建订单"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <!-- 内容区 -->
      <el-form
        :model="addForm"
        :rules="orderRules"
        ref="addFormRef"
        label-width="70px"
      >
        <!-- 要换下拉框 -->
        <el-form-item label="下单客户" prop="order_customer" label-width="80px">
          <el-select
            v-model="addForm.order_customer"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in customerList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="付款情况" prop="order_is_pay" label-width="80px">
          <template>
            <el-radio v-model="addForm.order_is_pay" label="true"
              >已付款</el-radio
            >
            <el-radio v-model="addForm.order_is_pay" label="false"
              >未付款</el-radio
            >
          </template>
        </el-form-item>
        <el-form-item label="产品名称" prop="order_product" label-width="80px">
          <el-input v-model="addForm.order_product"></el-input>
        </el-form-item>
        <el-form-item label="产品数量" prop="order_number" label-width="80px">
          <el-input v-model.number="addForm.order_number"></el-input>
        </el-form-item>
        <el-form-item label="订单金额" prop="order_price" label-width="80px">
          <el-input v-model="addForm.order_price"></el-input>
        </el-form-item>
        <el-form-item label="订单备注" prop="order_remark" label-width="80px">
          <el-input v-model="addForm.order_remark"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrder"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 修改订单信息的对话框 -->
    <el-dialog
      title="修改订单信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <!-- 内容区 -->
      <el-form
        :model="editForm"
        :rules="orderRules"
        ref="editFormRef"
        label-width="70px"
      >
        <!-- 要换下拉框 -->
        <el-form-item label="下单客户" prop="order_customer" label-width="80px">
          <el-select
            v-model="editForm.order_customer"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in customerList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="order_product" label-width="80px">
          <el-input v-model="editForm.order_product"></el-input>
        </el-form-item>
        <el-form-item label="产品数量" prop="order_number" label-width="80px">
          <el-input v-model.number="editForm.order_number"></el-input>
        </el-form-item>
        <el-form-item label="订单金额" prop="order_price" label-width="80px">
          <el-input v-model="editForm.order_price"></el-input>
        </el-form-item>
        <el-form-item label="订单备注" prop="order_remark" label-width="80px">
          <el-input v-model="editForm.order_remark"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCustomerInfo"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      // 订单列表
      orderList: [],
      // 客户列表
      customerList: [],
      // 订单总数
      total: 0,
      // 控制添加订单对话框的显示与隐藏
      addDialogVisible: false,
      // 添加订单的表单数据
      addForm: {
        order_id: '',
        order_admin1: '',
        order_product: '',
        order_number: '',
        order_price: '',
        order_time1: '',
        order_is_pay: '',
        order_customer: '',
        order_is_sale: false
      },
      // 控制修改订单对话框的显示与隐藏
      editDialogVisible: false,
      //修改表单信息
      editForm: {},
      //修改表单的验证规则对象
      orderRules: {
        order_product: [
          {
            required: true,
            message: '请输入订单产品名称',
            trigger: 'blur'
          }
        ],
        order_number: [
          {
            required: true,
            message: '请输入产品数量',
            trigger: 'blur'
          },
          { type: 'number', message: '商品数量必须为数字值' }
        ],
        order_is_pay: [
          {
            required: true,
            message: '请选择付款情况',
            trigger: 'blur'
          }
        ],
        order_price: [
          {
            required: true,
            message: '请输入订单金额',
            trigger: 'blur'
          }
        ],
        order_customer: [
          {
            required: true,
            message: '请输入下单客户',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getOrdersList()
    //获取客户列表，创建订单和修改时使用
    this.getCustomerList()
  },
  methods: {
    // 根据分页获取对应的订单列表
    async getOrdersList() {
      const { data: res } = await this.$http.get('allOrder', {
        params: this.queryInfo
      })
      if (res.numbers < 1) {
        return this.$message.error('获取订单列表失败！')
      }
      console.log(res)
      //赋值前清除，不然会有数据重复
      this.orderList = []
      //临时存储
      var arr = res.data
      //order_is_sale字段为false，则为待销售单
      for (let item of arr) {
        if (item.order_is_sale == false) {
          this.orderList.push(item)
        }
      }
      this.total = this.orderList.length
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getOrdersList()
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize
      this.getOrdersList()
    },
    // 展示订单编辑的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(
        'getUpdateOrder?order_id=' + id
      )
      if (res == null) {
        return this.$message.error('查询订单信息失败！')
      }
      this.editForm = res
      this.editDialogVisible = true
    },
    // 监听添加订单对话框的关闭事件
    addDialogClosed() {
      // 重置表单项
      this.$refs.addFormRef.resetFields()
    },
    //添加订单
    addOrder() {
      //发起添加订单请求+
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        let myDate = new Date()
        this.addForm.order_id = this.formatDate(myDate) + this.total - 1
        this.addForm.order_admin1 = window.sessionStorage.getItem('user')
        this.addForm.order_time1 = myDate
        console.log(this.addForm)
        const { data: res } = await this.$http.post('addOrder', this.addForm)
        if (res !== 'success') {
          return this.$message.error('添加订单信息失败')
        }
        this.$message.success('添加订单信息成功')
        // 隐藏添加订单对话框
        this.addDialogVisible = false
        // 重新获取订单列表数据
        this.getOrdersList()
      })
    },
    //修改订单信息并提交
    editCustomerInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //发起修改订单信息的数据请求
        const { data: res } = await this.$http.put('editOrder', this.editForm)
        if (res !== 'success') {
          return this.$message.error('修改数据失败！')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新订单数据列表
        this.getOrdersList()
        //提示修改成功
        this.$message.success('修改数据成功！')
      })
    },
    // 通过Id删除订单
    async removeById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该订单信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(
        'deleteOrder?order_id=' + id
      )
      if (res !== 'success') {
        return this.$message.error('删除订单信息失败!')
      }
      this.$message.success('删除订单信息成功!')
      this.getOrdersList()
    },
    //日期格式化，用来生成订单id
    formatDate(date) {
      let year = date.getFullYear()
      let mounth = date.getMonth() + 1
      mounth = mounth < 10 ? '0' + mounth : mounth
      let day = date.getDate()
      day = day < 10 ? '0' + day : day
      let hour = date.getHours()
      hour = hour < 10 ? '0' + hour : hour
      let minute = date.getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      let second = date.getSeconds()
      second = second < 10 ? '0' + second : second
      return year + mounth + day + hour + minute + second
    },
    //创建订单和修改订单时获取客户信息
    async getCustomerList() {
      const { data: res } = await this.$http.get('allCustomers')
      var arr = res.data
      for (let item of arr) {
        this.customerList.push({
          label: item.customer_name,
          value: item.customer_name
        })
      }
    },
    //确认收款
    async confirmPay(id) {
      console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将修改订单付款信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.put(
        `OrderPay?order_id=${id}&order_is_pay=true`
      )
      if (res !== 'success') {
        return this.$message.error('更新付款状态失败！')
      }
      this.$message.success('更新付款状态成功')
      this.getOrdersList()
    },
    //完成订单
    async finishOrder(order) {
      console.log(order)
      //以下操作获取所有商品信息，若订单商品在商品库搜索不到或库存数量不足，无法完成订单
      const { data: res2 } = await this.$http.get('allProducts')
      var productList = res2.data
      //判断改商品是否存在商品库
      var isExit = 0
      //判断库存是否足够
      var isEnough = 0
      console.log('prodct', productList)
      for (const item of productList) {
        //判断商品库存在商品否
        if (item.productName == order.order_product) {
          //存在
          isExit++
          //判断订单中产品数量是否小于库存数量
          if (order.order_number <= item.numbers) {
            isEnough++
          }
        }
      }
      if (!isExit) {
        return this.$message.error('商品库搜索不到改产品，无法完成订单！')
      }
      if (!isEnough) {
        return this.$message.error('商品库中库存不足，无法完成订单！')
      }
      //供应商名称，用来插入数据库
      var providerName = ''
      //获取供应商数据
      const { data: res3 } = await this.$http.get('allProviders')
      var providersList = res3.data
      console.log('供应商', providersList)
      for (let item of providersList) {
        if (item.provider_good == order.order_product) {
          providerName = item.provider_name
        }
      }
      const confirmResult = await this.$confirm(
        '此操作将修改订单为销售单, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      //满足以上条件后，可以发起完成订单请求
      //todo：商品库数量更新,插入供应商信息，另外销售单页面完成盈利分析，会员积分增长
      const { data: res } = await this.$http.put(
        `OrderStatusChange?order_id=${
          order.order_id
        }&order_is_sale=true&admin2=${window.sessionStorage.getItem(
          'user'
        )}&number=${order.order_number}&productName=${
          order.order_product
        }&providerName=${providerName}&customer_name=${
          order.order_customer
        }&order_price=${order.order_price}`
      )
      if (res !== 'success') {
        return this.$message.error('更新订单状态失败！')
      }
      this.getOrdersList()
      //更新会员积分
      const h = this.$createElement
      this.$message({
        message: h('p', null, [
          h(
            'span',
            null,
            '尊敬的' + order.order_customer + '会员，您的积分增加 '
          ),
          h('i', { style: 'color: teal' }, order.order_price + 100)
        ])
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-button--success {
  margin-left: 30px;
}
.el-button--danger {
  margin-left: 30px;
}
</style>
